package net.sf.odinms.client.messages;

import java.util.*;
import java.sql.*;
import net.sf.odinms.database.*;
import java.rmi.RemoteException;
import net.sf.odinms.client.IItem;
import net.sf.odinms.client.Item;
import net.sf.odinms.client.MapleCharacter;
import net.sf.odinms.client.MapleClient;
import net.sf.odinms.client.MapleInventoryType;
import net.sf.odinms.server.life.MapleMonster;
import net.sf.odinms.server.maps.*;
import net.sf.odinms.client.MapleStat;
import net.sf.odinms.client.MapleJob;
import net.sf.odinms.server.*;
import net.sf.odinms.server.life.*;
import net.sf.odinms.server.maps.*;
import net.sf.odinms.net.channel.ChannelServer;
import net.sf.odinms.tools.MaplePacketCreator;
import net.sf.odinms.net.world.remote.WorldChannelInterface;
import net.sf.odinms.net.world.remote.WorldLocation;
import net.sf.odinms.net.world.PlayerCoolDownValueHolder;
import net.sf.odinms.net.world.remote.CheaterData;

public class InternCommand {

    public static int getOptionalIntArg(String splitted[], int position, int def) {
        if (splitted.length > position) {
            try {
                return Integer.parseInt(splitted[position]);
            } catch (NumberFormatException nfe) {
                return def;
            }
        }
        return def;
    }

    public static boolean executeInternCommand(MapleClient c, MessageCallback mc, String line) {
        MapleCharacter player = c.getPlayer();
        ChannelServer cserv = c.getChannelServer(); //hairi
        String[] splitted = line.split(" ");
        //hairi 只有实习GM才可以用以下命令
        if (splitted[0].equals("!sxheal")) {
            player.setHp(player.getMaxHp());
            player.setMp(player.getMaxMp());
            player.updateSingleStat(MapleStat.HP, player.getMaxHp());
            player.updateSingleStat(MapleStat.MP, player.getMaxMp());
        /* } else if (splitted[0].equals("!sxhealall")) {
        for (MapleCharacter mch : c.getPlayer().getMap().getCharacters()) {
        if (mch != null) {
        mch.setHp(mch.getMaxHp());
        mch.updateSingleStat(MapleStat.HP, mch.getMaxHp());
        mch.setMp(mch.getMaxMp());
        mch.updateSingleStat(MapleStat.MP, mch.getMaxMp());
        }
        }*/
        } else if (splitted[0].equals("!sxback")) {
            MapleMap target = cserv.getMapFactory().getMap(100000000);
            MaplePortal targetPortal = target.getPortal(0);
            player.changeMap(target, targetPortal);
        } else if (splitted[0].equals("!sxlaba")) {
            MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
            int itemId = 5390001; //hairi 绚烂情景喇叭
            short quantity = 100; //hairi 100个喇叭
            IItem toDrop;
            if (ii.getInventoryType(itemId) == MapleInventoryType.EQUIP) {
                toDrop = ii.getEquipById(itemId);
            } else {
                toDrop = new Item(itemId, (byte) 0, (short) quantity);
            }
            StringBuilder logMsg = new StringBuilder("Created by ");
            logMsg.append(c.getPlayer().getName());
            logMsg.append(" using !drop. Quantity: ");
            logMsg.append(quantity);
            toDrop.log(logMsg.toString(), false);
            toDrop.setOwner("0");
            c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
        } else if (splitted[0].equals("!sxsds")) {
            MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
            int itemId = 5041000; //hairi 高级缩地石
            short quantity = 100; //hairi 100个
            IItem toDrop;
            if (ii.getInventoryType(itemId) == MapleInventoryType.EQUIP) {
                toDrop = ii.getEquipById(itemId);
            } else {
                toDrop = new Item(itemId, (byte) 0, (short) quantity);
            }
            StringBuilder logMsg = new StringBuilder("Created by ");
            logMsg.append(c.getPlayer().getName());
            logMsg.append(" using !drop. Quantity: ");
            logMsg.append(quantity);
            toDrop.log(logMsg.toString(), false);
            toDrop.setOwner("0");
            c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
        } else if (splitted[0].equals("!sxhsf")) {
            MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
            int itemId = 5130000; //hairi 护身符
            short quantity = 10; //hairi 10个
            IItem toDrop;
            if (ii.getInventoryType(itemId) == MapleInventoryType.EQUIP) {
                toDrop = ii.getEquipById(itemId);
            } else {
                toDrop = new Item(itemId, (byte) 0, (short) quantity);
            }
            StringBuilder logMsg = new StringBuilder("Created by ");
            logMsg.append(c.getPlayer().getName());
            logMsg.append(" using !drop. Quantity: ");
            logMsg.append(quantity);
            toDrop.log(logMsg.toString(), false);
            toDrop.setOwner("0");
            c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);

        } else if (splitted[0].equals("!sxonline")) {
            mc.dropMessage("<<当前频道所有在线玩家清单>>");
            c.getChannelServer();
            Collection chrs = ChannelServer.getInstance(c.getChannel()).getPlayerStorage().getAllCharacters();
            MapleCharacter chr;
            for (Iterator i$ = chrs.iterator(); i$.hasNext(); mc.dropMessage((new StringBuilder()).append("角色ID:").append(chr.getId()).append(" | 角色名:").append(chr.getName()).append(" | 地图代码:").append(chr.getMapId()).append(" | 等级:").append(chr.getLevel()).toString())) {
                chr = (MapleCharacter) i$.next();
            }
        } else if (splitted[0].equals("!sxonlineall")) {
            StringBuilder sb = new StringBuilder("<<所有频道所有在线玩家清单>>: ");
            mc.dropMessage(sb.toString());
            for (ChannelServer cs : ChannelServer.getAllInstances()) {
                //sb = new StringBuilder("[ 频道" + cs.getChannel() + "]");
                //mc.dropMessage(sb.toString());
                mc.dropMessage("[ 频道" + cs.getChannel() + "]");
                //sb = new StringBuilder();
                for (MapleCharacter chr : cs.getPlayerStorage().getAllCharacters()) {
                    //sb.append(MapleCharacterUtil.makeMapleReadable();
                    //mc.dropMessage(sb.toString());
                    mc.dropMessage("ID:" + chr.getId() + "/角色名:" + chr.getName() + "/地图:" + chr.getMapId() + "/等级:" + chr.getLevel() + "/点卷:" + chr.getNX() + "/金钱:" + chr.getMeso());
                }
            }
        } else if (splitted[0].equals("!sxsaveall")) {
            for (ChannelServer chan : ChannelServer.getAllInstances()) {
                for (MapleCharacter chr : chan.getPlayerStorage().getAllCharacters()) {
                    chr.saveToDB(true);
                }
            }
            mc.dropMessage("{ 系统信息 } 所有频道所有玩家的数据保存完毕.");
        /*} else if (splitted[0].equals("!sxclock")) {
        player.getMap().broadcastMessage(MaplePacketCreator.getClock(getOptionalIntArg(splitted, 1, 60)));
        } else if (splitted[0].equals("!sxdel")) {
        MapleMap map = c.getPlayer().getMap();
        double range = Double.POSITIVE_INFINITY;
        List<MapleMapObject> items = map.getMapObjectsInRange(c.getPlayer().getPosition(), range, Arrays.asList(MapleMapObjectType.ITEM));
        for (MapleMapObject itemmo : items) {
        map.removeMapObject(itemmo);
        map.broadcastMessage(MaplePacketCreator.removeItemFromMap(itemmo.getObjectId(), 0, c.getPlayer().getId()));
        }
        mc.dropMessage("『 系统提示 』 您清理了此地图上掉落的 " + items.size() + " 件物品.");
         */
        } else if (splitted[0].equals("!sxfenghao")) {
            int charid = Integer.parseInt(splitted[1]); //hairi 实习GM不能够去封GM
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterById(charid);
            if (!victim.isGM()) { //hairi 实习GM不能够去封GM
                if (victim != null) {
                    int mapid = 920011200;
                    MapleMap target = ChannelServer.getInstance(c.getChannel()).getMapFactory().getMap(mapid);
                    victim.changeMap(target, target.getPortal(0));
                    mc.dropMessage("『 系统提示 』 您已经成功对角色ID为 " + splitted[1] + " 的玩家进行了在线封号.");
                } else {
                    mc.dropMessage("『 系统提示 』 缺少命令参数,具体请参看GM命令介绍.");
                }
            } else {
                mc.dropMessage("『 系统提示 』 实习GM不能够封任何GM.");
            }
        } else if (splitted[0].equals("!sxlxfenghao")) {
            try {
                Connection con = DatabaseConnection.getConnection();
                PreparedStatement ps = con.prepareStatement("UPDATE characters SET map = ? WHERE id = ?");
                ps.setInt(1, 920011200); //封号地图
                ps.setInt(2, Integer.parseInt(splitted[1])); //被封角色ID
                ps.executeUpdate();
                ps.close();
                mc.dropMessage("『 系统提示 』 您已经成功对角色ID为 " + splitted[1] + " 的玩家进行了离线封号.");
            } catch (SQLException ex) {
                mc.dropMessage("『 系统提示 』 您已经<失败>对角色ID为 " + splitted[1] + " 的玩家进行了离线封号.");
                //log.error("Error while changing status", ex);
            }
        } else if (splitted[0].equals("!sxtplayer")) {
            int charid = Integer.parseInt(splitted[1]); //hairi 实习GM不能够去踢GM
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterById(charid);
            if (!victim.isGM()) {  //hairi 实习GM不能T掉GM
                victim.getClient().getSession().close();
                victim.getClient().disconnect();
                try {
                    victim.saveToDB(true);
                    cserv.removePlayer(victim);
                } catch (Exception e) {
                }
                mc.dropMessage("『 系统提示 』 指定的角色已经被T下线.");
            } else {
                mc.dropMessage("『 系统提示 』 实习GM不能够踢任何GM.");
            }
        } else if (splitted[0].equals("!sxwarp")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterById(Integer.parseInt(splitted[1]));
            if (victim != null) {
                MapleMap target = victim.getMap();
                c.getPlayer().changeMap(target, target.findClosestSpawnpoint(victim.getPosition()));
            } else {
                mc.dropMessage("『 系统提示 』 输入的角色ID不存在或不在线，无法传送到指定玩家身边.");
            }
        } else if (splitted[0].equals("!sxwarphere")) {
            int charid = Integer.parseInt(splitted[1]); //hairi 实习GM不能传送GM
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterById(charid);
            //if (!victim.isGM()) {  //hairi 不能将同是GM传送到身边
                victim.changeMap(c.getPlayer().getMap(), c.getPlayer().getMap().findClosestSpawnpoint(c.getPlayer().getPosition()));
            //} else {
            //    mc.dropMessage("『 系统提示 』 实习GM不能够传送任何GM.");
            //}
        } else if (splitted[0].equals("!sxwarpallhere")) { //召唤指定级别范围的玩家
            int minlevel = Integer.parseInt(splitted[1]); //最低级别
            int maxlevel = Integer.parseInt(splitted[2]); //最大级别
            for (MapleCharacter mch : cserv.getPlayerStorage().getAllCharacters()) {
                //if (!mch.isGM()) { //hairi 非管理员执行
                    if (mch.getLevel() >= minlevel && mch.getLevel() <= maxlevel) {
                        if (mch.getMapId() != c.getPlayer().getMapId()) {
                            mch.changeMap(c.getPlayer().getMap(), c.getPlayer().getPosition());
                        }
                    }
                //}
            }
        } else if (splitted[0].equals("!sxlevel")) {
            c.getPlayer().setExp(0);
            c.getPlayer().setLevel(getOptionalIntArg(splitted, 1, 1) - 1);
            c.getPlayer().levelUp();
            c.getPlayer().setExp(0);
            c.getPlayer().updateSingleStat(MapleStat.EXP, 0);
            mc.dropMessage("『 系统提示 』 实习GM您已经成功的调整了角色级别，请慎用该功能以免破坏游戏平衡性！");
        } else if (splitted[0].equals("!sxjob")) {
            int jobid = Integer.parseInt(splitted[1]);
            if (jobid < 910) {
                c.getPlayer().changeJob(MapleJob.getById(jobid));
                mc.dropMessage("『 系统提示 』 实习GM您已经成功的调整了角色职业，请慎用该功能以免破坏游戏平衡性！");
            } else {
                mc.dropMessage("『 系统提示 』 实习GM请您不要试图把自己修改成GM职业！");
            }
        /*} else if (splitted[0].equals("!sxmap")) {
        int mapid = Integer.parseInt(splitted[1]);
        if (mapid == 180000000) {
        mc.dropMessage("『 系统提示 』 实习GM请您不要试图把自己传送到GM专用地图！");
        } else {
        MapleMap target = cserv.getMapFactory().getMap(mapid);
        MaplePortal targetPortal = target.getPortal(0);
        player.changeMap(target, targetPortal);
        mc.dropMessage("『 系统提示 』 实习GM您已经成功的传送到指定地图！");
        }*/

        } else if (splitted[0].equals("!sxcharinfo")) {
            MapleCharacter other = cserv.getPlayerStorage().getCharacterById(Integer.parseInt(splitted[1]));
            if (!other.isGM()) {
                mc.dropMessage("角色ID为" + splitted[1] + "的玩家当前坐标X:" + other.getPosition().x + " Y:" + other.getPosition().y + "");
                mc.dropMessage("HP为:" + other.getHp() + "/" + other.getCurrentMaxHp() + "");
                mc.dropMessage("MP为:" + other.getMp() + "/" + other.getCurrentMaxMp() + "");
                mc.dropMessage("经验为:" + other.getExp() + "");
                mc.dropMessage("组队状态为:" + (other.getParty() != null) + " 交易状态为:" + (other.getTrade() != null) + "");
                mc.dropMessage("远程地址为:" + other.getClient().getSession().getRemoteAddress() + "");
            } else {
                mc.dropMessage("『 系统提示 』 实习GM请您不要试图去查询其他GM的信息！");
            }
        } else if (splitted[0].equals("!sxkillall")) {
            MapleMap map = c.getPlayer().getMap();
            double range = Double.POSITIVE_INFINITY;
            List<MapleMapObject> monsters = map.getMapObjectsInRange(c.getPlayer().getPosition(), range, Arrays.asList(MapleMapObjectType.MONSTER));
            for (MapleMapObject monstermo : monsters) {
                MapleMonster monster = (MapleMonster) monstermo;
                map.killMonster(monster, c.getPlayer(), false);
            }
            mc.dropMessage("{ 系统信息 } 您已经成功杀死当前地图上 " + monsters.size() + " 只怪物.");
        } else if (splitted[0].equals("!sxkillallremote")) { //hairi 杀死远程地图的怪
            MapleMap map = c.getChannelServer().getMapFactory().getMap(Integer.parseInt(splitted[1]));
            double range = Double.POSITIVE_INFINITY;
            List<MapleMapObject> monsters = map.getMapObjectsInRange(c.getPlayer().getPosition(), range, Arrays.asList(MapleMapObjectType.MONSTER));
            for (MapleMapObject monstermo : monsters) {
                MapleMonster monster = (MapleMonster) monstermo;
                map.killMonster(monster, c.getPlayer(), false);
                monster.giveExpToCharacter(player, monster.getExp(), true, 1); //hairi 杀死怪后是否得经验
            }
            mc.dropMessage("{ 系统信息 } 您已经成功杀死 " + splitted[1] + " 远程地图上的 " + monsters.size() + " 只怪物.");
        } else if (splitted[0].equals("!sxspawn")) {
            int monsterid = Integer.parseInt(splitted[1]);
            if (monsterid != 9400202 && monsterid != 9400203 && monsterid != 9400204) { //防止刷金水灵 银水灵 红水灵
                for (int i = 0; i < Math.min(Integer.parseInt(splitted[2]), 300); i++) {
                    MapleMonster mob = MapleLifeFactory.getMonster(monsterid);
                    c.getPlayer().getMap().spawnMonsterOnGroudBelow(mob, c.getPlayer().getPosition());
                }
            }
        } else if (splitted[0].equals("!sxdel")) {
            MapleMap map = c.getPlayer().getMap();
            double range = Double.POSITIVE_INFINITY;
            List<MapleMapObject> items = map.getMapObjectsInRange(c.getPlayer().getPosition(), range, Arrays.asList(MapleMapObjectType.ITEM));
            for (MapleMapObject itemmo : items) {
                map.removeMapObject(itemmo);
                map.broadcastMessage(MaplePacketCreator.removeItemFromMap(itemmo.getObjectId(), 0, c.getPlayer().getId()));
            }
            mc.dropMessage("『 系统提示 』 您清理了此地图上掉落的 " + items.size() + " 件物品.");
        } else if (splitted[0].equals("!sxgmexp")) {
            if (player.getGmHaveExp()) {
                player.setGmHaveExp(false);
                mc.dropMessage("『 系统提示 』您已经禁止得到打怪经验！");
            } else {
                player.setGmHaveExp(true);
                mc.dropMessage("『 系统提示 』您已经启用得到打怪经验！");
            }
        } else if (splitted[0].equals("!sxcheaters")) {
            try {
                List<CheaterData> cheaters = c.getChannelServer().getWorldInterface().getCheaters();
                for (int x = cheaters.size() - 1; x >= 0; x--) {
                    CheaterData cheater = cheaters.get(x);
                    mc.dropMessage(cheater.getInfo());
                }
            } catch (RemoteException e) {
                c.getChannelServer().reconnectWorld();
            }
        } else if (splitted[0].equals("!sxhelp")) {
            mc.dropMessage("=====================================================");
            mc.dropMessage("          快乐冒险世界 - 实习管理员帮助信息");
            mc.dropMessage("=====================================================");
            mc.dropMessage("!sxheal - 把自己的HP和MP加满");
            //mc.dropMessage("!sxhealall - 把地图里所有玩家的HP和MP加满");
            mc.dropMessage("!sxback - 返回射手村安全区");
            mc.dropMessage("!sxlaba - 掉落100个蓝色情景喇叭（赠送新人）");
            mc.dropMessage("!sxsds - 掉落100个高级瞬移之石（赠送新人）");
            mc.dropMessage("!sxhsf - 掉落10个护身符（赠送新人）");
            mc.dropMessage("!sxonline - 查看当前频道的在线玩家的信息");
            mc.dropMessage("!sxonlineall - 查看所有频道的在线玩家的信息");
            mc.dropMessage("!sxsaveall - 立即保存所有在线玩家的数据");
            //mc.dropMessage("!sxclock <秒数> - 在当前地图打开时间倒数器,单位秒钟.");
            mc.dropMessage("!sxfenghao <角色ID> - 在线封号,把玩家传送到无法出来的地图");
            mc.dropMessage("!sxlxfenghao <角色ID> - 离线封号,把玩家传送到无法出来的地图");
            mc.dropMessage("!sxtplayer <角色ID> - 踢指定的玩家离线");
            mc.dropMessage("!sxwarp <角色ID> - 传送到指定玩家身边");
            mc.dropMessage("!sxwarphere <角色ID> - 传送指定玩家到自己身边");
            mc.dropMessage("!sxwarpallhere <最小级别> <最大级别> - 传送指定级别范围的所有玩家到自己身边");
            mc.dropMessage("!sxlevel <等级> - 改变自己角色级别到指定级别");
            mc.dropMessage("!sxjob <职业ID> - 改变自己角色职业到指定职业");
            //mc.dropMessage("!sxmap <地图ID> - 传送自己到指定的游戏地图");
            mc.dropMessage("!sxcheaters - 查游戏外挂命令");
            mc.dropMessage("!sxcharinfo <角色ID> - 查询指定玩家的信息");
            mc.dropMessage("!sxkillall - 杀死当前地图里所有的怪物");
            mc.dropMessage("!sxkillallremote <地图ID> - 杀死远程地图里所有的怪物");
            mc.dropMessage("!sxdel - 清理此地图上掉落的所有物品");
            mc.dropMessage("!sxspawn <怪物ID> <数量> - 在当前位置刷出指定数量的怪物");
            mc.dropMessage("!sxgmexp - 禁止或启用GM打怪得经验功能，默认是有经验模式。");
            mc.dropMessage("===========================================================");
        } else {
            if (c.getPlayer().gmLevel() == 1) {
                mc.dropMessage("{ 系统命令 } 您输入的实习游戏管理员命令 " + splitted[0] + " 不存在!");
            }
            return false;
        }
        return true;
    }
}